import Session = Express.Session;
import {Request, Response, NextFunction} from "express";

import PWSApp from "../../core/app";
import IndexAction from "./act.index";
import {Magics} from "../../core/magics";
import * as utils from '../../core/utils';
import {ErrCode} from "../../core/error.code";
import BaseLoader from '../../core/base.loader';

import UploadXls from "./upload.xls";
import UploadImgs from "./upload.imgs";
import UploadFile from "./upload.file";

class AdminActLoader extends BaseLoader {
    constructor(app: PWSApp) {
        super(app);
    }

    protected _load(): void {
        new UploadImgs(this.app);
        new UploadXls(this.app);
        new UploadFile(this.app);
        new IndexAction(this.app);
    }

    protected _checkLogin(): void {
        let needLogin = new RegExp('/admin(?!\/(login|resetpwd|sendresetpwd|notifier))');
        this.app.registerRoutes(needLogin, (req: Request, res: Response, next: NextFunction) => {
            if( this._isLogin(req.session) || 1) {
                next();
                return;
            }
            res.send( { err_code: ErrCode.UserNotLogin } );
        });
    }

    protected _isLogin(sess: Session): boolean {
        return !!(sess && sess[Magics.SessSysUser] && utils.isObjectId(sess[Magics.SessSysUser].uid));
    }
}

export = function(app: PWSApp) {
    new AdminActLoader(app);
}